home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Metrowerks CodeWarrior / Java Support / Java_Source / Java2 / src / java / lang / Thread.java < prev    next >
Encoding:
Java Source  |  1999-05-28  |  42.4 KB  |  1,143 lines  |  [TEXT/CWIE]

  1. /*
  2.  * @(#)Thread.java    1.97 98/11/05
  3.  *
  4.  * Copyright 1994-1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. package java.lang;
  16.  
  17. import java.security.AccessController;
  18. import java.security.AccessControlContext;
  19.  
  20. /**
  21.  * A <i>thread</i> is a thread of execution in a program. The Java 
  22.  * Virtual Machine allows an application to have multiple threads of 
  23.  * execution running concurrently. 
  24.  * <p>
  25.  * Every thread has a priority. Threads with higher priority are 
  26.  * executed in preference to threads with lower priority. Each thread 
  27.  * may or may not also be marked as a daemon. When code running in 
  28.  * some thread creates a new <code>Thread</code> object, the new 
  29.  * thread has its priority initially set equal to the priority of the 
  30.  * creating thread, and is a daemon thread if and only if the 
  31.  * creating thread is a daemon. 
  32.  * <p>
  33.  * When a Java Virtual Machine starts up, there is usually a single 
  34.  * non-daemon thread (which typically calls the method named 
  35.  * <code>main</code> of some designated class). The Java Virtual 
  36.  * Machine continues to execute threads until either of the following 
  37.  * occurs: 
  38.  * <ul>
  39.  * <li>The <code>exit</code> method of class <code>Runtime</code> has been 
  40.  *     called and the security manager has permitted the exit operation 
  41.  *     to take place. 
  42.  * <li>All threads that are not daemon threads have died, either by 
  43.  *     returning from the call to the <code>run</code> method or by 
  44.  *     throwing an exception that propagates beyond the <code>run</code>
  45.  *     method.
  46.  * </ul>
  47.  * <p>
  48.  * There are two ways to create a new thread of execution. One is to 
  49.  * declare a class to be a subclass of <code>Thread</code>. This 
  50.  * subclass should override the <code>run</code> method of class 
  51.  * <code>Thread</code>. An instance of the subclass can then be 
  52.  * allocated and started. For example, a thread that computes primes 
  53.  * larger than a stated value could be written as follows: 
  54.  * <p><hr><blockquote><pre>
  55.  *     class PrimeThread extends Thread {
  56.  *         long minPrime;
  57.  *         PrimeThread(long minPrime) {
  58.  *             this.minPrime = minPrime;
  59.  *         }
  60.  * 
  61.  *         public void run() {
  62.  *             // compute primes larger than minPrime
  63.  *              . . .
  64.  *         }
  65.  *     }
  66.  * </pre></blockquote><hr>
  67.  * <p>
  68.  * The following code would then create a thread and start it running: 
  69.  * <p><blockquote><pre>
  70.  *     PrimeThread p = new PrimeThread(143);
  71.  *     p.start();
  72.  * </pre></blockquote>
  73.  * <p>
  74.  * The other way to create a thread is to declare a class that 
  75.  * implements the <code>Runnable</code> interface. That class then 
  76.  * implements the <code>run</code> method. An instance of the class can 
  77.  * then be allocated, passed as an argument when creating 
  78.  * <code>Thread</code>, and started. The same example in this other 
  79.  * style looks like the following: 
  80.  * <p><hr><blockquote><pre>
  81.  *     class PrimeRun implements Runnable {
  82.  *         long minPrime;
  83.  *         PrimeRun(long minPrime) {
  84.  *             this.minPrime = minPrime;
  85.  *         }
  86.  * 
  87.  *         public void run() {
  88.  *             // compute primes larger than minPrime
  89.  *              . . .
  90.  *         }
  91.  *     }
  92.  * </pre></blockquote><hr>
  93.  * <p>
  94.  * The following code would then create a thread and start it running: 
  95.  * <p><blockquote><pre>
  96.  *     PrimeRun p = new PrimeRun(143);
  97.  *     new Thread(p).start();
  98.  * </pre></blockquote>
  99.  * <p>
  100.  * Every thread has a name for identification purposes. More than 
  101.  * one thread may have the same name. If a name is not specified when 
  102.  * a thread is created, a new name is generated for it. 
  103.  *
  104.  * @author  unascribed
  105.  * @version 1.97, 11/05/98
  106.  * @see     java.lang.Runnable
  107.  * @see     java.lang.Runtime#exit(int)
  108.  * @see     java.lang.Thread#run()
  109.  * @see     java.lang.Thread#stop()
  110.  * @since   JDK1.0
  111.  */
  112. public
  113. class Thread implements Runnable {
  114.     /* Make sure registerNatives is the first thing <clinit> does. */
  115.     private static native void registerNatives();
  116.     static {
  117.         registerNatives();
  118.     }
  119.  
  120.     private char    name[];
  121.     private int         priority;
  122.     private Thread    threadQ;
  123.     private long    eetop;
  124.  
  125.     /* Whether or not to single_step this thread. */
  126.     private boolean    single_step;
  127.  
  128.     /* Whether or not the thread is a daemon thread. */
  129.     private boolean    daemon = false;
  130.  
  131.     /* Whether or not this thread was asked to exit before it runs.*/
  132.     private boolean    stillborn = false;
  133.  
  134.     /* What will be run. */
  135.     private Runnable target;
  136.  
  137.     /* The group of this thread */
  138.     private ThreadGroup    group;
  139.  
  140.     /* The context ClassLoader for this thread */
  141.     private ClassLoader contextClassLoader;
  142.  
  143.     /* The inherited AccessControlContext of this thread */
  144.     private AccessControlContext inheritedAccessControlContext;
  145.  
  146.     /* For autonumbering anonymous threads. */
  147.     private static int threadInitNumber;
  148.     private static synchronized int nextThreadNum() {
  149.     return threadInitNumber++;
  150.     }
  151.  
  152.     // static permissions
  153.     private static RuntimePermission stopThreadPermission;
  154.  
  155.     /* List of InheritableThreadLocal values pertaining to this thread.
  156.      * This list is maintained by the InheritableThreadLocal class.  We call
  157.      * InheritableThreadLocal.bequeath on this list at thread creation
  158.      * time to pass our values on to our child. */
  159.     InheritableThreadLocal.Entry values = null;
  160.  
  161.     /**
  162.      * The minimum priority that a thread can have. 
  163.      */
  164.     public final static int MIN_PRIORITY = 1;
  165.  
  166.    /**
  167.      * The default priority that is assigned to a thread. 
  168.      */
  169.     public final static int NORM_PRIORITY = 5;
  170.  
  171.     /**
  172.      * The maximum priority that a thread can have. 
  173.      */
  174.     public final static int MAX_PRIORITY = 10;
  175.  
  176.     /**
  177.      * Returns a reference to the currently executing thread object.
  178.      *
  179.      * @return  the currently executing thread.
  180.      */
  181.     public static native Thread currentThread();
  182.  
  183.     /**
  184.      * Causes the currently executing thread object to temporarily pause 
  185.      * and allow other threads to execute. 
  186.      */
  187.     public static native void yield();
  188.  
  189.     /**    
  190.      * Causes the currently executing thread to sleep (temporarily cease 
  191.      * execution) for the specified number of milliseconds. The thread 
  192.      * does not lose ownership of any monitors.
  193.      *
  194.      * @param      millis   the length of time to sleep in milliseconds.
  195.      * @exception  InterruptedException if another thread has interrupted
  196.      *             the current thread.  The <i>interrupted status</i> of the
  197.      *             current thread is cleared when this exception is thrown.
  198.      * @see        java.lang.Object#notify()
  199.      */
  200.     public static native void sleep(long millis) throws InterruptedException;
  201.  
  202.     /**
  203.      * Causes the currently executing thread to sleep (cease execution) 
  204.      * for the specified number of milliseconds plus the specified number 
  205.      * of nanoseconds. The thread does not lose ownership of any monitors.
  206.      *
  207.      * @param      millis   the length of time to sleep in milliseconds.
  208.      * @param      nanos    0-999999 additional nanoseconds to sleep.
  209.      * @exception  IllegalArgumentException  if the value of millis is 
  210.      *             negative or the value of nanos is not in the range 
  211.      *             0-999999.
  212.      * @exception  InterruptedException if another thread has interrupted
  213.      *             the current thread.  The <i>interrupted status</i> of the
  214.      *             current thread is cleared when this exception is thrown.
  215.      * @see        java.lang.Object#notify()
  216.      */
  217.     public static void sleep(long millis, int nanos) 
  218.     throws InterruptedException {
  219.     if (millis < 0) {
  220.             throw new IllegalArgumentException("timeout value is negative");
  221.     }
  222.  
  223.     if (nanos < 0 || nanos > 999999) {
  224.             throw new IllegalArgumentException(
  225.                 "nanosecond timeout value out of range");
  226.     }
  227.  
  228.     if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  229.         millis++;
  230.     }
  231.  
  232.     sleep(millis);
  233.     }
  234.  
  235.     /**
  236.      * Initialize a Thread.
  237.      *
  238.      * @param g the Thread group
  239.      * @param target the object whose run() method gets called
  240.      * @param name the name of the new Thread
  241.      */
  242.     private void init(ThreadGroup g, Runnable target, String name){
  243.     Thread parent = currentThread();
  244.     if (g == null) {
  245.         /* Determine if it's an applet or not */
  246.         SecurityManager security = System.getSecurityManager();
  247.         
  248.         /* If there is a security manager, ask the security manager
  249.            what to do. */
  250.         if (security != null) {
  251.         g = security.getThreadGroup();
  252.         }
  253.  
  254.         /* If the security doesn't have a strong opinion of the matter
  255.            use the parent thread group. */
  256.         if (g == null) {
  257.         g = parent.getThreadGroup();
  258.         }
  259.     }
  260.  
  261.     /* checkAccess regardless of whether or not threadgroup is
  262.            explicitly passed in. */
  263.     g.checkAccess();        
  264.  
  265.     this.group = g;
  266.     this.daemon = parent.isDaemon();
  267.     this.priority = parent.getPriority();
  268.     this.name = name.toCharArray();
  269.     this.contextClassLoader = parent.contextClassLoader;
  270.     this.inheritedAccessControlContext = AccessController.getContext();
  271.     this.target = target;
  272.     setPriority(priority);
  273.         InheritableThreadLocal.bequeath(parent, this);
  274.     g.add(this);
  275.     }
  276.  
  277.    /**
  278.      * Allocates a new <code>Thread</code> object. This constructor has 
  279.      * the same effect as <code>Thread(null, null,</code>
  280.      * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is 
  281.      * a newly generated name. Automatically generated names are of the 
  282.      * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer. 
  283.      * <p>
  284.      * Threads created this way must have overridden their
  285.      * <code>run()</code> method to actually do anything.  An example
  286.      * illustrating this method being used follows:
  287.      * <p><blockquote><pre>
  288.      *     import java.lang.*;
  289.      *
  290.      *     class plain01 implements Runnable {
  291.      *         String name; 
  292.      *         plain01() {
  293.      *             name = null;
  294.      *         }
  295.      *         plain01(String s) {
  296.      *             name = s;
  297.      *         }
  298.      *         public void run() {
  299.      *             if (name == null)
  300.      *                 System.out.println("A new thread created");
  301.      *             else
  302.      *                 System.out.println("A new thread with name " + name +
  303.      *                                    " created");
  304.      *         }
  305.      *     }
  306.      *     class threadtest01 {
  307.      *         public static void main(String args[] ) {
  308.      *             int failed = 0 ;
  309.      *
  310.      *             <b>Thread t1 = new Thread();</b>  
  311.      *             if (t1 != null)
  312.      *                 System.out.println("new Thread() succeed");
  313.      *             else {
  314.      *                 System.out.println("new Thread() failed"); 
  315.      *                 failed++; 
  316.      *             }
  317.      *         }
  318.      *     }
  319.      * </pre></blockquote>
  320.      *
  321.      * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
  322.      *          java.lang.Runnable, java.lang.String)
  323.      */
  324.     public Thread() {
  325.     init(null, null, "Thread-" + nextThreadNum());
  326.     }
  327.  
  328.     /**
  329.      * Allocates a new <code>Thread</code> object. This constructor has 
  330.      * the same effect as <code>Thread(null, target,</code>
  331.      * <i>gname</i><code>)</code>, where <i>gname</i> is 
  332.      * a newly generated name. Automatically generated names are of the 
  333.      * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer. 
  334.      *
  335.      * @param   target   the object whose <code>run</code> method is called.
  336.      * @see     java.lang.Thread#Thread(java.lang.ThreadGroup, 
  337.      *          java.lang.Runnable, java.lang.String)
  338.      */
  339.     public Thread(Runnable target) {
  340.     init(null, target, "Thread-" + nextThreadNum());
  341.     }
  342.  
  343.     /**
  344.      * Allocates a new <code>Thread</code> object. This constructor has 
  345.      * the same effect as <code>Thread(group, target,</code>
  346.      * <i>gname</i><code>)</code>, where <i>gname</i> is 
  347.      * a newly generated name. Automatically generated names are of the 
  348.      * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer. 
  349.      *
  350.      * @param      group    the thread group.
  351.      * @param      target   the object whose <code>run</code> method is called.
  352.      * @exception  SecurityException  if the current thread cannot create a
  353.      *             thread in the specified thread group.
  354.      * @see        java.lang.Thread#Thread(java.lang.ThreadGroup, 
  355.      *             java.lang.Runnable, java.lang.String)
  356.      */
  357.     public Thread(ThreadGroup group, Runnable target) {
  358.     init(group, target, "Thread-" + nextThreadNum());
  359.     }
  360.  
  361.     /**
  362.      * Allocates a new <code>Thread</code> object. This constructor has 
  363.      * the same effect as <code>Thread(null, null, name)</code>. 
  364.      *
  365.      * @param   name   the name of the new thread.
  366.      * @see     java.lang.Thread#Thread(java.lang.ThreadGroup, 
  367.      *          java.lang.Runnable, java.lang.String)
  368.      */
  369.     public Thread(String name) {
  370.     init(null, null, name);
  371.     }
  372.  
  373.     /**
  374.      * Allocates a new <code>Thread</code> object. This constructor has 
  375.      * the same effect as <code>Thread(group, null, name)</code> 
  376.      *
  377.      * @param      group   the thread group.
  378.      * @param      name    the name of the new thread.
  379.      * @exception  SecurityException  if the current thread cannot create a
  380.      *               thread in the specified thread group.
  381.      * @see        java.lang.Thread#Thread(java.lang.ThreadGroup, 
  382.      *          java.lang.Runnable, java.lang.String)
  383.      */
  384.     public Thread(ThreadGroup group, String name) {
  385.     init(group, null, name);
  386.     }
  387.  
  388.     /**
  389.      * Allocates a new <code>Thread</code> object. This constructor has 
  390.      * the same effect as <code>Thread(null, target, name)</code>. 
  391.      *
  392.      * @param   target   the object whose <code>run</code> method is called.
  393.      * @param   name     the name of the new thread.
  394.      * @see     java.lang.Thread#Thread(java.lang.ThreadGroup, 
  395.      *          java.lang.Runnable, java.lang.String)
  396.      */
  397.     public Thread(Runnable target, String name) {
  398.     init(null, target, name);
  399.     }
  400.  
  401.     /**
  402.      * Allocates a new <code>Thread</code> object so that it has 
  403.      * <code>target</code> as its run object, has the specified 
  404.      * <code>name</code> as its name, and belongs to the thread group 
  405.      * referred to by <code>group</code>.
  406.      * <p>
  407.      * If <code>group</code> is <code>null</code>, the group is
  408.      * set to be the same ThreadGroup as 
  409.      * the thread that is creating the new thread. 
  410.      * 
  411.      * <p>If there is a security manager, its <code>checkAccess</code> 
  412.      * method is called with the ThreadGroup as its argument.
  413.      * This may result in a SecurityException.
  414.      * <p>
  415.      * If the <code>target</code> argument is not <code>null</code>, the 
  416.      * <code>run</code> method of the <code>target</code> is called when 
  417.      * this thread is started. If the target argument is 
  418.      * <code>null</code>, this thread's <code>run</code> method is called 
  419.      * when this thread is started. 
  420.      * <p>
  421.      * The priority of the newly created thread is set equal to the 
  422.      * priority of the thread creating it, that is, the currently running 
  423.      * thread. The method <code>setPriority</code> may be used to 
  424.      * change the priority to a new value. 
  425.      * <p>
  426.      * The newly created thread is initially marked as being a daemon 
  427.      * thread if and only if the thread creating it is currently marked 
  428.      * as a daemon thread. The method <code>setDaemon </code> may be used 
  429.      * to change whether or not a thread is a daemon. 
  430.      *
  431.      * @param      group     the thread group.
  432.      * @param      target   the object whose <code>run</code> method is called.
  433.      * @param      name     the name of the new thread.
  434.      * @exception  SecurityException  if the current thread cannot create a
  435.      *               thread in the specified thread group.
  436.      * @see        java.lang.Runnable#run()
  437.      * @see        java.lang.Thread#run()
  438.      * @see        java.lang.Thread#setDaemon(boolean)
  439.      * @see        java.lang.Thread#setPriority(int)
  440.      * @see        java.lang.ThreadGroup#checkAccess()
  441.      * @see        SecurityManager#checkAccess
  442.      */
  443.     public Thread(ThreadGroup group, Runnable target, String name) {
  444.     init(group, target, name);
  445.     }
  446.  
  447.     /**
  448.      * Causes this thread to begin execution; the Java Virtual Machine 
  449.      * calls the <code>run</code> method of this thread. 
  450.      * <p>
  451.      * The result is that two threads are running concurrently: the 
  452.      * current thread (which returns from the call to the 
  453.      * <code>start</code> method) and the other thread (which executes its 
  454.      * <code>run</code> method). 
  455.      *
  456.      * @exception  IllegalThreadStateException  if the thread was already
  457.      *               started.
  458.      * @see        java.lang.Thread#run()
  459.      * @see        java.lang.Thread#stop()
  460.      */
  461.     public synchronized native void start();
  462.  
  463.     /**
  464.      * If this thread was constructed using a separate 
  465.      * <code>Runnable</code> run object, then that 
  466.      * <code>Runnable</code> object's <code>run</code> method is called; 
  467.      * otherwise, this method does nothing and returns. 
  468.      * <p>
  469.      * Subclasses of <code>Thread</code> should override this method. 
  470.      *
  471.      * @see     java.lang.Thread#start()
  472.      * @see     java.lang.Thread#stop()
  473.      * @see     java.lang.Thread#Thread(java.lang.ThreadGroup, 
  474.      *          java.lang.Runnable, java.lang.String)
  475.      * @see     java.lang.Runnable#run()
  476.      */
  477.     public void run() {
  478.     if (target != null) {
  479.         target.run();
  480.     }
  481.     }
  482.  
  483.     /**
  484.      * This method is called by the system to give a Thread
  485.      * a chance to clean up before it actually exits.
  486.      */
  487.     private void exit() {
  488.     if (group != null) {
  489.         group.remove(this);
  490.         group = null;
  491.     }
  492.     /* Aggressively null object connected to Thread: see bug 4006245 */
  493.     target = null;
  494.     }
  495.  
  496.     /** 
  497.      * Forces the thread to stop executing.
  498.      * <p>
  499.      * If there is a security manager installed, its <code>checkAccess</code>
  500.      * method is called with <code>this</code> 
  501.      * as its argument. This may result in a 
  502.      * <code>SecurityException</code> being raised (in the current thread). 
  503.      * <p>
  504.      * If this thread is different from the current thread (that is, the current
  505.      * thread is trying to stop a thread other than itself), the
  506.      * security manager's <code>checkPermission</code> method (with a
  507.      * <code>RuntimePermission("stopThread")</code> argument) is called in
  508.      * addition.
  509.      * Again, this may result in throwing a 
  510.      * <code>SecurityException</code> (in the current thread). 
  511.      * <p>
  512.      * The thread represented by this thread is forced to stop whatever 
  513.      * it is doing abnormally and to throw a newly created 
  514.      * <code>ThreadDeath</code> object as an exception. 
  515.      * <p>
  516.      * It is permitted to stop a thread that has not yet been started. 
  517.      * If the thread is eventually started, it immediately terminates. 
  518.      * <p>
  519.      * An application should not normally try to catch 
  520.      * <code>ThreadDeath</code> unless it must do some extraordinary 
  521.      * cleanup operation (note that the throwing of 
  522.      * <code>ThreadDeath</code> causes <code>finally</code> clauses of 
  523.      * <code>try</code> statements to be executed before the thread 
  524.      * officially dies).  If a <code>catch</code> clause catches a 
  525.      * <code>ThreadDeath</code> object, it is important to rethrow the 
  526.      * object so that the thread actually dies. 
  527.      * <p>
  528.      * The top-level error handler that reacts to otherwise uncaught 
  529.      * exceptions does not print out a message or otherwise notify the 
  530.      * application if the uncaught exception is an instance of 
  531.      * <code>ThreadDeath</code>. 
  532.      *
  533.      * @exception  SecurityException  if the current thread cannot 
  534.      *               modify this thread.
  535.      * @see        java.lang.Thread#interrupt()
  536.      * @see        java.lang.Thread#checkAccess()
  537.      * @see        java.lang.Thread#run()
  538.      * @see        java.lang.Thread#start()
  539.      * @see        java.lang.ThreadDeath
  540.      * @see        java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
  541.      *             java.lang.Throwable)
  542.      * @see        SecurityManager#checkAccess(Thread)
  543.      * @see        SecurityManager#checkPermission
  544.      * @deprecated This method is inherently unsafe.  Stopping a thread with
  545.      *         Thread.stop causes it to unlock all of the monitors that it
  546.      *         has locked (as a natural consequence of the unchecked
  547.      *         <code>ThreadDeath</code> exception propagating up the stack).  If
  548.      *       any of the objects previously protected by these monitors were in
  549.      *       an inconsistent state, the damaged objects become visible to
  550.      *       other threads, potentially resulting in arbitrary behavior.  Many
  551.      *       uses of <code>stop</code> should be replaced by code that simply
  552.      *       modifies some variable to indicate that the target thread should
  553.      *       stop running.  The target thread should check this variable  
  554.      *       regularly, and return from its run method in an orderly fashion
  555.      *       if the variable indicates that it is to stop running.  If the
  556.      *       target thread waits for long periods (on a condition variable,
  557.      *       for example), the <code>interrupt</code> method should be used to
  558.      *       interrupt the wait. 
  559.      *       For more information, see 
  560.      *       <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why 
  561.      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  562.      */
  563.     public final void stop() {
  564.     synchronized (this) {
  565.         SecurityManager security = System.getSecurityManager();
  566.         if (security != null) {
  567.         checkAccess();
  568.         if (this != Thread.currentThread()) {
  569.             if (stopThreadPermission == null)
  570.             stopThreadPermission =
  571.                 new RuntimePermission("stopThread");
  572.             security.checkPermission(stopThreadPermission);
  573.         }
  574.         }
  575.         resume(); // Wake up thread if it was suspended; no-op otherwise
  576.         stop0(new ThreadDeath());
  577.     }
  578.     }
  579.  
  580.     /**
  581.      * Forces the thread to stop executing.
  582.      * <p>
  583.      * If there is a security manager installed, the <code>checkAccess</code>
  584.      * method of this thread is called, which may result in a 
  585.      * <code>SecurityException</code> being raised (in the current thread). 
  586.      * <p>
  587.      * If this thread is different from the current thread (that is, the current
  588.      * thread is trying to stop a thread other than itself) or
  589.      * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
  590.      * security manager's <code>checkPermission</code> method (with the
  591.      * <code>RuntimePermission("stopThread")</code> argument) is called in
  592.      * addition.
  593.      * Again, this may result in throwing a 
  594.      * <code>SecurityException</code> (in the current thread). 
  595.      * <p>
  596.      * If the argument <code>obj</code> is null, a 
  597.      * <code>NullPointerException</code> is thrown (in the current thread). 
  598.      * <p>
  599.      * The thread represented by this thread is forced to complete 
  600.      * whatever it is doing abnormally and to throw the 
  601.      * <code>Throwable</code> object <code>obj</code> as an exception. This 
  602.      * is an unusual action to take; normally, the <code>stop</code> method 
  603.      * that takes no arguments should be used. 
  604.      * <p>
  605.      * It is permitted to stop a thread that has not yet been started. 
  606.      * If the thread is eventually started, it immediately terminates. 
  607.      *
  608.      * @param      obj   the Throwable object to be thrown.
  609.      * @exception  SecurityException  if the current thread cannot modify
  610.      *               this thread.
  611.      * @see        java.lang.Thread#interrupt()
  612.      * @see        java.lang.Thread#checkAccess()
  613.      * @see        java.lang.Thread#run()
  614.      * @see        java.lang.Thread#start()
  615.      * @see        java.lang.Thread#stop()
  616.      * @see        SecurityManager#checkAccess(Thread)
  617.      * @see        SecurityManager#checkPermission
  618.      * @deprecated This method is inherently unsafe.  See {@link #stop}
  619.      *        (with no arguments) for details.  An additional danger of this
  620.      *        method is that it may be used to generate exceptions that the
  621.      *        target thread is unprepared to handle (including checked
  622.      *        exceptions that the thread could not possibly throw, were it
  623.      *        not for this method).
  624.      *        For more information, see 
  625.      *        <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why 
  626.      *        are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  627.      */
  628.     public final synchronized void stop(Throwable obj) {
  629.     SecurityManager security = System.getSecurityManager();
  630.     if (security != null) {
  631.         checkAccess();
  632.         if ((this != Thread.currentThread()) ||
  633.         (!(obj instanceof ThreadDeath))) {
  634.         if (stopThreadPermission == null)
  635.             stopThreadPermission = new RuntimePermission("stopThread");
  636.         security.checkPermission(stopThreadPermission);
  637.         }
  638.     }
  639.     resume(); // Wake up thread if it was suspended; no-op otherwise
  640.     stop0(obj);
  641.     }
  642.  
  643.     /**
  644.      * Interrupts this thread.
  645.      * 
  646.      * <p>
  647.      * First the <code>checkAccess</code> method of this thread is called 
  648.      * with no arguments. This may result in throwing a 
  649.      * <code>SecurityException</code>. 
  650.      * 
  651.      * @exception  SecurityException  if the current thread cannot modify
  652.      *         this thread.
  653.      */
  654.     // Note that this method is not synchronized.  Three reasons for this:
  655.     // 1) It changes the API.
  656.     // 2) It's another place where the system could hang.
  657.     // 3) All we're doing is turning on a one-way bit.  It doesn't matter
  658.     //    exactly when it's done WRT probes via the interrupted() method.
  659.     public void interrupt() {
  660.     checkAccess();
  661.     interrupt0();
  662.     }
  663.  
  664.     /**
  665.      * Tests whether the current thread has been interrupted.  The
  666.      * <i>interrupted status</i> of the thread is cleared by this method.  In
  667.      * other words, if this method were to be called twice in succession, the
  668.      * second call would return false (unless the current thread were
  669.      * interrupted again, after the first call had cleared its interrupted
  670.      * status and before the second call had examined it).
  671.      *
  672.      * @return  <code>true</code> if the current thread has been interrupted;
  673.      *          <code>false</code> otherwise.
  674.      * @see java.lang.Thread#isInterrupted()
  675.      */
  676.     public static boolean interrupted() {
  677.     return currentThread().isInterrupted(true);
  678.     }
  679.  
  680.     /**
  681.      * Tests whether this thread has been interrupted.  The <i>interrupted
  682.      * status</i> of the thread is unaffected by this method.
  683.      *
  684.      * @return  <code>true</code> if this thread has been interrupted;
  685.      *          <code>false</code> otherwise.
  686.      * @see     java.lang.Thread#interrupted()
  687.      */
  688.     public boolean isInterrupted() {
  689.     return isInterrupted(false);
  690.     }
  691.  
  692.     /**
  693.      * Tests if some Thread has been interrupted.  The interrupted state
  694.      * is reset or not based on the value of ClearInterrupted that is
  695.      * passed.
  696.      */
  697.     private native boolean isInterrupted(boolean ClearInterrupted);
  698.  
  699.     /**
  700.      * Destroys this thread, without any cleanup. Any monitors it has 
  701.      * locked remain locked. (This method is not implemented.)
  702.      */
  703.     public void destroy() {
  704.     throw new NoSuchMethodError();
  705.     }
  706.  
  707.     /**
  708.      * Tests if this thread is alive. A thread is alive if it has 
  709.      * been started and has not yet died. 
  710.      *
  711.      * @return  <code>true</code> if this thread is alive;
  712.      *          <code>false</code> otherwise.
  713.      */
  714.     public final native boolean isAlive();
  715.  
  716.     /**
  717.      * Suspends this thread.
  718.      * <p>
  719.      * First, the <code>checkAccess</code> method of this thread is called 
  720.      * with no arguments. This may result in throwing a 
  721.      * <code>SecurityException </code>(in the current thread). 
  722.      * <p>
  723.      * If the thread is alive, it is suspended and makes no further 
  724.      * progress unless and until it is resumed. 
  725.      *
  726.      * @exception  SecurityException  if the current thread cannot modify
  727.      *               this thread.
  728.      * @see #checkAccess
  729.      * @deprecated   This method has been deprecated, as it is
  730.      *   inherently deadlock-prone.  If the target thread holds a lock on the
  731.      *   monitor protecting a critical system resource when it is suspended, no
  732.      *   thread can access this resource until the target thread is resumed. If
  733.      *   the thread that would resume the target thread attempts to lock this
  734.      *   monitor prior to calling <code>resume</code>, deadlock results.  Such
  735.      *   deadlocks typically manifest themselves as "frozen" processes.
  736.      *   For more information, see 
  737.      *   <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why 
  738.      *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  739.      */
  740.     public final void suspend() {
  741.     checkAccess();
  742.     suspend0();
  743.     }
  744.  
  745.     /**
  746.      * Resumes a suspended thread.
  747.      * <p>
  748.      * First, the <code>checkAccess</code> method of this thread is called 
  749.      * with no arguments. This may result in throwing a 
  750.      * <code>SecurityException</code> (in the current thread). 
  751.      * <p>
  752.      * If the thread is alive but suspended, it is resumed and is 
  753.      * permitted to make progress in its execution. 
  754.      *
  755.      * @exception  SecurityException  if the current thread cannot modify this
  756.      *               thread.
  757.      * @see        #checkAccess
  758.      * @see        java.lang.Thread#suspend()
  759.      * @deprecated This method exists solely for use with {@link #suspend},
  760.      *     which has been deprecated because it is deadlock-prone.
  761.      *     For more information, see 
  762.      *     <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why 
  763.      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  764.      */
  765.     public final void resume() {
  766.     checkAccess();
  767.     resume0();
  768.     }
  769.  
  770.     /**
  771.      * Changes the priority of this thread. 
  772.      * <p>
  773.      * First the <code>checkAccess</code> method of this thread is called 
  774.      * with no arguments. This may result in throwing a 
  775.      * <code>SecurityException</code>. 
  776.      * <p>
  777.      * Otherwise, the priority of this thread is set to the smaller of 
  778.      * the specified <code>newPriority</code> and the maximum permitted 
  779.      * priority of the thread's thread group. 
  780.      *
  781.      * @exception  IllegalArgumentException  If the priority is not in the
  782.      *               range <code>MIN_PRIORITY</code> to
  783.      *               <code>MAX_PRIORITY</code>.
  784.      * @exception  SecurityException  if the current thread cannot modify
  785.      *               this thread.
  786.      * @see        java.lang.Thread#checkAccess()
  787.      * @see        java.lang.Thread#getPriority()
  788.      * @see        java.lang.Thread#getThreadGroup()
  789.      * @see        java.lang.Thread#MAX_PRIORITY
  790.      * @see        java.lang.Thread#MIN_PRIORITY
  791.      * @see        java.lang.ThreadGroup#getMaxPriority()
  792.      */
  793.     public final void setPriority(int newPriority) {
  794.     checkAccess();
  795.     if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
  796.         throw new IllegalArgumentException();
  797.     }
  798.     if (newPriority > group.getMaxPriority()) {
  799.         newPriority = group.getMaxPriority();
  800.     }
  801.     setPriority0(priority = newPriority);
  802.     }
  803.  
  804.     /**
  805.      * Returns this thread's priority.
  806.      *
  807.      * @return  this thread's name.
  808.      * @see     java.lang.Thread#setPriority(int)
  809.      */
  810.     public final int getPriority() {
  811.     return priority;
  812.     }
  813.  
  814.     /**
  815.      * Changes the name of this thread to be equal to the argument 
  816.      * <code>name</code>. 
  817.      * <p>
  818.      * First the <code>checkAccess</code> method of this thread is called 
  819.      * with no arguments. This may result in throwing a 
  820.      * <code>SecurityException</code>. 
  821.      *
  822.      * @param      name   the new name for this thread.
  823.      * @exception  SecurityException  if the current thread cannot modify this
  824.      *               thread.
  825.      * @see        java.lang.Thread#checkAccess()
  826.      * @see        java.lang.Thread#getName()
  827.      */
  828.     public final void setName(String name) {
  829.     checkAccess();
  830.     this.name = name.toCharArray();
  831.     }
  832.  
  833.     /**
  834.      * Returns this thread's name.
  835.      *
  836.      * @return  this thread's name.
  837.      * @see     java.lang.Thread#setName(java.lang.String)
  838.      */
  839.     public final String getName() {
  840.     return String.valueOf(name);
  841.     }
  842.  
  843.     /**
  844.      * Returns the thread group to which this thread belongs. 
  845.      * This method returns null if this thread has died
  846.      * (been stopped).
  847.      *
  848.      * @return  this thread's thread group.
  849.      */
  850.     public final ThreadGroup getThreadGroup() {
  851.     return group;
  852.     }
  853.  
  854.     /**
  855.      * Returns the current number of active threads in this thread's 
  856.      * thread group.
  857.      *
  858.      * @return  the current number of threads in this thread's thread group.
  859.      */
  860.     public static int activeCount() {
  861.     return currentThread().getThreadGroup().activeCount();
  862.     }
  863.  
  864.     /**
  865.      * Copies into the specified array every active thread in 
  866.      * this thread's thread group and its subgroups. This method simply 
  867.      * calls the <code>enumerate</code> method of this thread's thread 
  868.      * group with the array argument. 
  869.      * <p>
  870.      * First, if there is a security manager, that <code>enumerate</code>
  871.      * method calls the security
  872.      * manager's <code>checkAccess</code> method 
  873.      * with the thread group as its argument. This may result 
  874.      * in throwing a <code>SecurityException</code>. 
  875.      *
  876.      * @return  the number of threads put into the array.
  877.      *
  878.      * @exception  SecurityException  if a security manager exists and its  
  879.      *             <code>checkAccess</code> method doesn't allow the operation.
  880.      * @see     java.lang.ThreadGroup#enumerate(java.lang.Thread[])
  881.      * @see     java.lang.SecurityManager#checkAccess(java.lang.ThreadGroup)
  882.      */
  883.     public static int enumerate(Thread tarray[]) {
  884.     return currentThread().getThreadGroup().enumerate(tarray);
  885.     }
  886.  
  887.     /**
  888.      * Counts the number of stack frames in this thread. The thread must 
  889.      * be suspended. 
  890.      *
  891.      * @return     the number of stack frames in this thread.
  892.      * @exception  IllegalThreadStateException  if this thread is not
  893.      *             suspended.
  894.      * @deprecated The definition of this call depends on {@link #suspend},
  895.      *           which is deprecated.  Further, the results of this call
  896.      *           were never well-defined.
  897.      */
  898.     public native int countStackFrames();
  899.  
  900.     /**
  901.      * Waits at most <code>millis</code> milliseconds for this thread to 
  902.      * die. A timeout of <code>0</code> means to wait forever. 
  903.      *
  904.      * @param      millis   the time to wait in milliseconds.
  905.      * @exception  InterruptedException if another thread has interrupted
  906.      *             the current thread.  The <i>interrupted status</i> of the
  907.      *             current thread is cleared when this exception is thrown.
  908.      */
  909.     public final synchronized void join(long millis) 
  910.     throws InterruptedException {
  911.     long base = System.currentTimeMillis();
  912.     long now = 0;
  913.  
  914.     if (millis < 0) {
  915.             throw new IllegalArgumentException("timeout value is negative");
  916.     }
  917.  
  918.     if (millis == 0) {
  919.         while (isAlive()) {
  920.         wait(0);
  921.         }
  922.     } else {
  923.         while (isAlive()) {
  924.         long delay = millis - now;
  925.         if (delay <= 0) {
  926.             break;
  927.         }
  928.         wait(delay);
  929.         now = System.currentTimeMillis() - base;
  930.         }
  931.     }
  932.     }
  933.  
  934.     /**
  935.      * Waits at most <code>millis</code> milliseconds plus 
  936.      * <code>nanos</code> nanoseconds for this thread to die. 
  937.      *
  938.      * @param      millis   the time to wait in milliseconds.
  939.      * @param      nanos    0-999999 additional nanoseconds to wait.
  940.      * @exception  IllegalArgumentException  if the value of millis is negative
  941.      *               the value of nanos is not in the range 0-999999.
  942.      * @exception  InterruptedException if another thread has interrupted
  943.      *             the current thread.  The <i>interrupted status</i> of the
  944.      *             current thread is cleared when this exception is thrown.
  945.      */
  946.     public final synchronized void join(long millis, int nanos) 
  947.     throws InterruptedException {
  948.  
  949.     if (millis < 0) {
  950.             throw new IllegalArgumentException("timeout value is negative");
  951.     }
  952.  
  953.     if (nanos < 0 || nanos > 999999) {
  954.             throw new IllegalArgumentException(
  955.                 "nanosecond timeout value out of range");
  956.     }
  957.  
  958.     if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  959.         millis++;
  960.     }
  961.  
  962.     join(millis);
  963.     }
  964.  
  965.     /**
  966.      * Waits for this thread to die. 
  967.      *
  968.      * @exception  InterruptedException if another thread has interrupted
  969.      *             the current thread.  The <i>interrupted status</i> of the
  970.      *             current thread is cleared when this exception is thrown.
  971.      */
  972.     public final void join() throws InterruptedException {
  973.     join(0);
  974.     }
  975.  
  976.     /**
  977.      * Prints a stack trace of the current thread. This method is used 
  978.      * only for debugging. 
  979.      *
  980.      * @see     java.lang.Throwable#printStackTrace()
  981.      */
  982.     public static void dumpStack() {
  983.     new Exception("Stack trace").printStackTrace();
  984.     }
  985.  
  986.     /**
  987.      * Marks this thread as either a daemon thread or a user thread. The 
  988.      * Java Virtual Machine exits when the only threads running are all 
  989.      * daemon threads. 
  990.      * <p>
  991.      * This method must be called before the thread is started. 
  992.       * <p>
  993.      * This method first calls the <code>checkAccess</code> method 
  994.      * of this thread 
  995.      * with no arguments. This may result in throwing a 
  996.      * <code>SecurityException </code>(in the current thread). 
  997.     *
  998.      * @param      on   if <code>true</code>, marks this thread as a
  999.      *                  daemon thread.
  1000.      * @exception  IllegalThreadStateException  if this thread is active.
  1001.      * @exception  SecurityException  if the current thread cannot modify
  1002.      *               this thread.
  1003.      * @see        java.lang.Thread#isDaemon()
  1004.      * @see          #checkAccess
  1005.      */
  1006.     public final void setDaemon(boolean on) {
  1007.     checkAccess();
  1008.     if (isAlive()) {
  1009.         throw new IllegalThreadStateException();
  1010.     }
  1011.     daemon = on;
  1012.     }
  1013.  
  1014.     /**
  1015.      * Tests if this thread is a daemon thread.
  1016.      *
  1017.      * @return  <code>true</code> if this thread is a daemon thread;
  1018.      *          <code>false</code> otherwise.
  1019.      * @see     java.lang.Thread#setDaemon(boolean)
  1020.      */
  1021.     public final boolean isDaemon() {
  1022.     return daemon;
  1023.     }
  1024.  
  1025.     /**
  1026.      * Determines if the currently running thread has permission to 
  1027.      * modify this thread. 
  1028.      * <p>
  1029.      * If there is a security manager, its <code>checkAccess</code> method 
  1030.      * is called with this thread as its argument. This may result in 
  1031.      * throwing a <code>SecurityException</code>. 
  1032.      * <p>
  1033.      * Note: This method was mistakenly non-final in JDK 1.1.
  1034.      * It has been made final in JDK 1.2.
  1035.      *
  1036.      * @exception  SecurityException  if the current thread is not allowed to
  1037.      *               access this thread.
  1038.      * @see        java.lang.SecurityManager#checkAccess(java.lang.Thread)
  1039.      */
  1040.     public final void checkAccess() {
  1041.     SecurityManager security = System.getSecurityManager();
  1042.     if (security != null) {
  1043.         security.checkAccess(this);
  1044.     }
  1045.     }
  1046.  
  1047.     /**
  1048.      * Returns a string representation of this thread, including the 
  1049.      * thread's name, priority, and thread group.
  1050.      *
  1051.      * @return  a string representation of this thread.
  1052.      */
  1053.     public String toString() {
  1054.     if (getThreadGroup() != null) {
  1055.         return "Thread[" + getName() + "," + getPriority() + "," + 
  1056.                     getThreadGroup().getName() + "]";
  1057.     } else {
  1058.         return "Thread[" + getName() + "," + getPriority() + "," + 
  1059.                     "" + "]";
  1060.     }
  1061.     }
  1062.  
  1063.     /**    
  1064.      * Returns the context ClassLoader for this Thread. The context
  1065.      * ClassLoader is provided by the creator of the thread for use
  1066.      * by code running in this thread when loading classes and resources.
  1067.      * If not set, the default is the ClassLoader context of the parent
  1068.      * Thread. The context ClassLoader of the primordial thread is
  1069.      * typically set to the class loader used to load the application.
  1070.      *
  1071.      * <p>First, if there is a security manager, and the caller's class
  1072.      * loader is not null and the caller's class loader is not the same as or
  1073.      * an ancestor of the context class loader for the thread whose
  1074.      * context class loader is being requested, then the security manager's
  1075.      * <code>checkPermission</code> 
  1076.      * method is called with a 
  1077.      * <code>RuntimePermission("getClassLoader")</code> permission
  1078.      *  to see if it's ok to get the context ClassLoader.. 
  1079.      *
  1080.      * @return the context ClassLoader for this Thread
  1081.      *
  1082.      * @throws SecurityException
  1083.      *        if a security manager exists and its 
  1084.      *        <code>checkPermission</code> method doesn't allow 
  1085.      *        getting the context ClassLoader.
  1086.      * 
  1087.      * @see SecurityManager#checkPermission
  1088.      * @see java.lang.RuntimePermission
  1089.      * 
  1090.      * @since JDK1.2
  1091.      */
  1092.     public ClassLoader getContextClassLoader() {
  1093.     if (contextClassLoader == null)
  1094.         return null;
  1095.     SecurityManager sm = System.getSecurityManager();
  1096.     if (sm != null) {
  1097.         ClassLoader ccl = ClassLoader.getCallerClassLoader();
  1098.         if (ccl != null && ccl != contextClassLoader && 
  1099.                     !contextClassLoader.isAncestor(ccl)) {
  1100.         sm.checkPermission(ClassLoader.getGetClassLoaderPerm());
  1101.         }
  1102.     }
  1103.     return contextClassLoader;
  1104.     }
  1105.  
  1106.     /**   
  1107.      * Sets the context ClassLoader for this Thread. The context
  1108.      * ClassLoader can be set when a thread is created, and allows
  1109.      * the creator of the thread to provide the appropriate class loader
  1110.      * to code running in the thread when loading classes and resources.
  1111.      *
  1112.      * <p>First, if there is a security manager, its <code>checkPermission</code> 
  1113.      * method is called with a 
  1114.      * <code>RuntimePermission("setContextClassLoader")</code> permission
  1115.      *  to see if it's ok to set the context ClassLoader.. 
  1116.      *
  1117.      * @param cl the context ClassLoader for this Thread
  1118.      * 
  1119.      * @exception  SecurityException  if the current thread cannot set the 
  1120.      * context ClassLoader.
  1121.      * 
  1122.      * @see SecurityManager#checkPermission
  1123.      * @see java.lang.RuntimePermission
  1124.      * 
  1125.      * @since JDK1.2 
  1126.      */
  1127.     public void setContextClassLoader(ClassLoader cl) {
  1128.     SecurityManager sm = System.getSecurityManager();
  1129.     if (sm != null) {
  1130.         sm.checkPermission(new RuntimePermission("setContextClassLoader"));
  1131.     }
  1132.     contextClassLoader = cl;
  1133.     }
  1134.  
  1135.     /* Some private helper methods */
  1136.     private native void setPriority0(int newPriority);
  1137.     private native void stop0(Object o);
  1138.     private native void suspend0();
  1139.     private native void resume0();
  1140.     private native void interrupt0();
  1141.  
  1142. }
  1143.